import { getChanceResult, getCustomItemList, getPriceString, LineHeight, saveStrToFile, takePriceList } from "../utils/mirUtil"
import { getArrayItem, getRandomListByNum, isNull, randomInRange } from "../utils/utls"
import { getCustomAbbKey } from "../测试/测试"
import { getItemMangae, getSkillId, getSkillName, getSlaveManage } from "../系统功能/GlobalObjectManage"
import { ActorCustomKeyList, ChanceData, GmSkill, HumanCustomSkill, HumanSkillList, MaxChanceNum, PriceData } from "../配置/基础配置"
import { CheckPrice, CheckType, ItemAddPointList, ItemCheckSet, ItemCustomEnum, ItemCustomSet } from "../配置/鉴定系统/鉴定系统"

export function Main(Npc: TNormNpc, Player: TPlayObject, Args: TArgs) {
    let startY = 5
    let str = '<{S=放入物品;C=251;X=320;Y=70}>'
    let item: TUserItem = Player.GetCustomItem(0)
    if (!item) {
        str += `<{S=请放入需要鉴定的物品;C=251;X=0;Y=${startY}}>`
    }
    else {
        // for (let i = Player.MaxBagSize - 1; i >= 0; i--) //循环背包
        // {
        //     let AItem: TUserItem = Player.GetBagItem(i); //取出一个背包物品 
        //     if (AItem) {
        //         console.log(AItem.Name)
        //     }
        // }

        let isCheck = item.GetOutWay2(ItemCustomEnum.Check)
        let price0 = getPriceList(item, 0)
        if (!price0) {
            Player.MessageBox("请放入正确的物品")
            return
        }

        if (isCheck) {
            str += `<{S=该物品已鉴定,不可免费鉴定,收费鉴定只能更新自定义属性;C=255;X=0;Y=${startY}}>`
            startY += 15;

            let price1 = getPriceList(item, 1)
            let obj = getPriceString(price0, 0, startY)
            startY = obj.y;
            // console.log(obj.y)
            str += obj.str;
            str += `<{S=开始鉴定;C=251;X=0;Y=${startY}}/@鉴定.开始鉴定(0,${CheckType.Custom})>`
            startY += 15;

            obj = getPriceString(price1, 0, startY)
            // console.log(obj.y)
            str += obj.str;
            startY = obj.y;
            str += `<{S=开始鉴定;C=251;X=0;Y=${startY}}/@鉴定.开始鉴定(1,${CheckType.Custom})>`
            startY += 15;

        }
        else {
            str += `<{S=该物品未鉴定,可免费鉴定;C=255;X=0;Y=${startY}}>`
            str += `<{S=开始鉴定;C=251;X=0;Y=${startY + 15}}/@鉴定.开始鉴定(0,${CheckType.All})>`
        }
    }
    Npc.SayEx(Player, "OK框", str);
}

export function 放入物品(Npc: TNormNpc, Player: TPlayObject, Args: TArgs) {
    Main(Npc, Player, Args)
}

export function 取出物品(Npc: TNormNpc, Player: TPlayObject, Args: TArgs) {
    // let str = `<{S=确定;C=251;X=340;Y=90}/@鉴定.NextPage()>`
    // Npc.SayEx(Player, "OK框", str);
    Main(Npc, Player, Args)
}

export function 开始鉴定(Npc: TNormNpc, Player: TPlayObject, Args: TArgs) {
    let item: TUserItem = Player.GetCustomItem(0)

    if (!item) {
        Player.MessageBox("请放入物品")
    }
    else {
        let lvIndex: number = getItemMangae().getLvIndexByItemName(item.Name);
        let priceIndex = Args.Int[0]
        let checkType = Args.Int[1] || CheckType.All
        // console.log(lvIndex)
        if (lvIndex == null || lvIndex === undefined) {
            Player.MessageBox("请放入正确的物品")
        }
        else {
            checkItems(item, Player, checkType, false, priceIndex)
        }
    }
}

export function 查看人物属性(Npc: TNormNpc, Player: TPlayObject, Args: TArgs) {
    let array: Array<number> = getAllCustomAbility(Player);
    let str = ''
    let x1 = 0;
    let y1 = 0;
    let x2 = 200;

    let x = x1;
    let y = y1;
    for (let i = 0; i < ItemCustomSet.length; i++) {
        let item = ItemCustomSet[i]
        str += `<{S=${item.text}:;C=255;X=${x};Y=${y}}>`
        str += `<{S=${array[i]};C=250;Y=${y}}>`
        str += `<{S=(最大值${item.max});C=251;Y=${y}}>`
        let tmpi = i % 2;
        if (tmpi) {
            y += LineHeight;
            x = x1
        }
        else {
            x = x2;
        }
    }

    Npc.Say(Player, str);
}

function getPriceList(item: TUserItem, priceIndex: number): Array<PriceData> {
    let lvIndex: number = getItemMangae().getLvIndexByItemName(item.Name);
    if (isNull(lvIndex)) {
        return null;
    }
    let price: Array<PriceData> = CheckPrice[priceIndex][lvIndex]
    return price;
}

/**
 * 鉴定物品
 * @param item  物品
 * @param play  人物
 * @param checkType 鉴定类型
 * @param isPicker 是否拾取
 * @param priceIndex 价格类型
 * @param isTest 是否测试
 */
export function checkItems(aitem: TUserItem, play: TPlayObject, checkType: CheckType, isPicker?: boolean, priceIndex?: number, isTest?: number) {
    if (aitem) {
        let isCheck = aitem.GetOutWay2(ItemCustomEnum.Check)
        if (isCheck && isPicker) {
            return;
        }
        let lvIndex: number = getItemMangae().getLvIndexByItemName(aitem.Name);
        // console.log("lvIndex:" + lvIndex)
        if (lvIndex < 0) {
            return;
        }

        checkType = checkType || CheckType.All;
        //如果已经鉴定 则收取物品
        if (isCheck && !isTest) {
            let price: Array<PriceData> = getPriceList(aitem, priceIndex || 0)
            let array: Array<number> = getCustomItemList(play)
            if (!takePriceList(price, play, '鉴定', true, array)) {
                return
            }
        }

        if (isTest) {
            let base = ItemCheckSet.Base;
            for (let key in base) {
                let item: Array<ChanceData> = getArrayItem(base[key], lvIndex) as Array<ChanceData>
                if (item.length > 0) {
                    let num = item[item.length - 1].max;
                    aitem[key] = num;
                }
                else {
                    aitem[key] = 0;
                }

            }

            let addPoint = ItemCheckSet.AddPoint;

            for (let i = 0; i < addPoint.length; i++) {
                let item: Array<ChanceData> = getArrayItem(addPoint[i], lvIndex) as Array<ChanceData>
                let num = 0
                if (item.length > 0) {
                    num = item[item.length - 1].max;
                }
                let addPointItem: TAddPointItem = aitem.GetAddPoint(i);
                addPointItem.SetValueType(ItemAddPointList[i].index)
                addPointItem.SetValue(num)

            }

            //自定义属性
            if (isTest === 1) {
                let custom = ItemCheckSet.Custom;

                for (let i = 0; i < custom.length; i++) {
                    let item: Array<ChanceData> = getArrayItem(custom[i], lvIndex) as Array<ChanceData>
                    let num = item[item.length - 1].max;
                    aitem.SetOutWay1(i, i + 1)
                    aitem.SetOutWay2(i, num)
                }

                if ([5, 6, 10, 11].includes(aitem.StdMode)) {

                    let skillList = getArrayItem(ItemCheckSet.skill, lvIndex).skillList
                    let skill = skillList[randomInRange(skillList.length)]
                    let skillId = getSkillId(skill.skillName)
                    let skillLevel = skill.levelChance[skill.levelChance.length - 1].max

                    if (skillLevel > 0) {
                        // console.log(`鉴定:${aitem.Name} ${skill.skillName} ${skillId} ${skillLevel}`)
                        let index = ItemCustomEnum.AddSkill + 1;
                        aitem.SetOutWay1(ItemCustomEnum.AddSkill, index)
                        aitem.SetOutWay2(ItemCustomEnum.AddSkill, skillId)
                        aitem.SetOutWay3(ItemCustomEnum.AddSkill, skillLevel)
                        // console.log(`鉴定:${index} ${aitem.GetOutWay2(ItemCustomEnum.AddSkill)} ${aitem.GetOutWay3(ItemCustomEnum.AddSkill)} `)

                        aitem.Rename(`${aitem.Name}(${skill.skillName})`)
                        // if (skillLevel > 4) {
                        //     aitem.SetCustomCaption(0, `附加技能:${skill.skillName}(强化${skillLevel - 4}级)`)
                        // }
                        // else {
                        //     aitem.SetCustomCaption(0, `附加技能:${skill.skillName}(${skillLevel - 1}级)`)
                        // }
                    }

                    // console.log(aitem.GetCustomDesc())
                }


            }


        }
        else {
            //极品属性
            if (checkType === CheckType.All || checkType === CheckType.Base) {
                let base = ItemCheckSet.Base;
                for (let key in base) {
                    let item: Array<ChanceData> = getArrayItem(base[key], lvIndex) as Array<ChanceData>
                    let num = getChanceResult(item);
                    aitem[key] = num;
                }
            }

            //元素属性
            if (checkType === CheckType.All || checkType === CheckType.AddPoint) {
                let addPoint = ItemCheckSet.AddPoint;

                for (let i = 0; i < addPoint.length; i++) {
                    let item: Array<ChanceData> = getArrayItem(addPoint[i], lvIndex) as Array<ChanceData>
                    let num = getChanceResult(item);
                    let addPointItem: TAddPointItem = aitem.GetAddPoint(i);
                    addPointItem.SetValueType(ItemAddPointList[i].index)
                    addPointItem.SetValue(num)
                }
            }



            //自定义属性
            if (checkType === CheckType.All || checkType === CheckType.Custom) {

                let CustomNum: Array<number> = ItemCheckSet.CustomNum;
                //自定义属性最大条数
                let maxNum: number = getArrayItem(CustomNum, lvIndex)
                let custom = ItemCheckSet.Custom;

                //清理鉴定属性
                for (let i = 0; i < custom.length; i++) {
                    aitem.SetOutWay1(i, 0)
                    aitem.SetOutWay2(i, 0)
                }


                //附加技能
                if ([5, 6, 10, 11].includes(aitem.StdMode)) {

                    //清理技能
                    aitem.SetOutWay1(ItemCustomEnum.AddSkill, 0)
                    aitem.SetOutWay2(ItemCustomEnum.AddSkill, 0)
                    aitem.SetOutWay3(ItemCustomEnum.AddSkill, 0)
                    aitem.Rename(aitem.Name)

                    let num: number = randomInRange(MaxChanceNum);
                    let skillList: any = getArrayItem(ItemCheckSet.skill, lvIndex)

                    if (num < skillList.chance) {
                        let list: Array<any> = skillList.skillList
                        let skill = list[randomInRange(list.length)]
                        let skillId = getSkillId(skill.skillName)


                        let levelChance: Array<ChanceData> = skill.levelChance as Array<ChanceData>
                        let skillLevel = getChanceResult(levelChance);



                        if (skillLevel > 0) {
                            let index = ItemCustomEnum.AddSkill + 1;
                            aitem.SetOutWay1(ItemCustomEnum.AddSkill, index)
                            aitem.SetOutWay2(ItemCustomEnum.AddSkill, skillId)
                            aitem.SetOutWay3(ItemCustomEnum.AddSkill, skillLevel)
                            aitem.Rename(`${aitem.Name}(${skill.skillName})`)
                            maxNum--;
                        }
                    }


                }

                //自定义属性

                //生成随机序列
                let list = getRandomListByNum(custom.length);

                for (let i = 0; i < custom.length; i++) {
                    let item: Array<ChanceData> = getArrayItem(custom[list[i]], lvIndex) as Array<ChanceData>

                    let num = getChanceResult(item);
                    if (num > 0) {
                        aitem.SetOutWay1(list[i], list[i] + 1)
                        aitem.SetOutWay2(list[i], num)
                        maxNum--;
                    }
                    if (maxNum <= 0) {
                        break;
                    }
                }

                // console.log(maxNum)
            }
        }

        aitem.SetOutWay2(ItemCustomEnum.Check, 1)
        play.UpdateItem(aitem)
        if (!isPicker && !isTest) {
            play.RemoveItemFromUIContainer(0)
            play.MessageBox('鉴定成功!')
            play.CloseWindow("OK框")
        }
    }

}

//获取所有的自定义属性和
export function getAllCustomAbility(play: TPlayObject): Array<number> {
    let array: Array<number> = []
    for (let i = 0; i < ItemCustomSet.length; i++) {
        let key = getCustomAbbKey(i)
        array.push(play.V[key] || 0)
    }
    // console.log(JSON.stringify(array))
    for (let j = TItemWhere.wDress; j <= TItemWhere.wCharm; j++) {
        let item: TUserItem = play.GetArmItem(j);
        if (item) {
            for (let i = 0; i < ItemCustomSet.length; i++) {
                let num = item.GetOutWay2(i);
                array[i] += num;
            }
        }
    }
    return array;
}

/**
 * 切换装备时候检查自定义属性
 * @param play 
 */
export function changeCustomAbility(play: TPlayObject): void {
    let array: Array<number> = getAllCustomAbility(play);
    for (let i = 0; i < ItemCustomSet.length; i++) {
        if (array[i] > ItemCustomSet[i].max) {
            array[i] = ItemCustomSet[i].max
        }
        play.SetNVar(ActorCustomKeyList[i], array[i]);
        // console.log(play.GetNVar(ActorCustomKeyList[i]) + " " + array[i])
    }

    // play.SetNVar(0, 50)
    // console.log("N0变量：" + play.GetNVar(0))


    let skillList: Array<string> = [].concat(HumanSkillList[play.Job], HumanCustomSkill);
    if (play.IsAdmin) {
        skillList = skillList.concat(GmSkill);
    }

    // console.log(skillList)
    let weapon: TUserItem = play.Weapon;
    let dress: TUserItem = play.Dress;
    // let itemList = [play.Weapon, play.Dress]

    //装备附加的技能
    let addSkill = [];
    if (weapon) {
        let skillId = weapon.GetOutWay2(ItemCustomEnum.AddSkill);
        let skillLevel = weapon.GetOutWay3(ItemCustomEnum.AddSkill) - 1;
        let skillName = getSkillName(skillId)
        // console.log(`武器:${skillName} ${skillId}`)
        if (skillName && skillLevel >= 0) {
            addSkill.push({
                skillName,
                skillLevel,
            })
        }
    }
    if (dress) {
        let skillId = dress.GetOutWay2(ItemCustomEnum.AddSkill);
        let skillLevel = dress.GetOutWay3(ItemCustomEnum.AddSkill) - 1;
        let skillName = getSkillName(skillId)
        // console.log(`衣服:${skillName} ${skillId}`)
        if (skillName && skillLevel >= 0) {
            addSkill.push({
                skillName,
                skillLevel,
            })
        }
    }

    // console.log(JSON.stringify(addSkill))

    //检查技能
    for (let i = play.SkillCount - 1; i >= 0; i--) {
        let skill: TUserMagic = play.GetSkills(i);
        if (!skillList.includes(skill.Name)) {
            let flag = false;
            for (let j = 0; j < addSkill.length; j++) {
                let item = addSkill[j];
                // console.log(JSON.stringify(item))
                if (item.skillName === skill.Name) {
                    flag = true;
                    let lv = 0;
                    let skillLevel = 0
                    if (item.skillLevel >= 3) {
                        skillLevel = 3;
                        lv = item.skillLevel - 3;
                    }
                    else {
                        skillLevel = item.skillLevel
                    }

                    play.ChangeSkillLevel(skill.Name, skillLevel)
                    skill.SetStrengthen(lv)
                    // console.log(`${item.skillName} ${skillLevel}  ${lv} ${skill.GetStrengthen()}`)
                    addSkill.splice(j, 1)
                    break;
                }
            }
            if (!flag) {
                play.DelSkill(skill.Name);
            }
        }
    }

    if (addSkill.length > 0) {
        for (let j = 0; j < addSkill.length; j++) {
            let item = addSkill[j];
            if (skillList.includes(item.skillName)) {
                continue
            }
            // console.log(JSON.stringify(item))

            let lv = 0;
            let skillLevel = 0
            if (item.skillLevel >= 3) {
                skillLevel = 3;
                lv = item.skillLevel - 3;
            }
            else {
                skillLevel = item.skillLevel
            }
            play.AddSkill(item.skillName, skillLevel);

            if (lv > 0) {
                let skill: TUserMagic = play.FindSkill(item.skillName)
                skill.SetStrengthen(lv)
            }
        }
    }

    //检查宝宝
    getSlaveManage().checkAllSlave(play)

}


export function checkItemCustomAbi(play: TPlayObject) {
    let custom = ItemCheckSet.Custom;

    for (let j = TItemWhere.wDress; j <= TItemWhere.wCharm; j++) {
        let aitem: TUserItem = play.GetArmItem(j);
        if (aitem) {
            let lvIndex: number = getItemMangae().getLvIndexByItemName(aitem.Name);
            if (lvIndex >= 0) {
                for (let i = 0; i < ItemCustomSet.length; i++) {
                    let num = aitem.GetOutWay2(i);
                    let item: Array<ChanceData> = getArrayItem(custom[i], lvIndex) as Array<ChanceData>
                    let max = item[item.length - 1].max;
                    if (num > max) {
                        aitem.SetOutWay2(i, max);
                    }
                }
            }

        }
    }
}